<?php


namespace App\Models\CacheModel;


use app\common\lib\SensorsData;
use App\Models\Api\BaseCache;
use App\Models\Api\Goods;
use think\Exception;
use think\Log;
use AstroTool\Cache\CacheManage;

class BirthBoon extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_birthday_boon';
    protected $cacheModel = 'coupon.birth';
    protected $cacheModel1 = 'coupon.register_package';
    public $errorMsg = '';

    private $couponTypeName = [
        1 => '折扣',
        2 => '立减',
        3 => '满减',
        4 => '随机',
        5 => '免费',
    ];
    /**
     * 获取生日优惠信息
     * @return array
     * @throws \Exception
     */
    public function getBirthBoon()
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->getDataAndSet(function ()
            {
                try
                {   // 获取生日权益数据
                    $data = $this->alias('b')
                        ->join('wechat_backup_07_18_14_43_00.zl_coupon_attr c', 'b.c_id=c.id')
                        ->where('b.status', 1)
                        ->where('b.type', 1) // 生日权益 type= 1生日权益 2新手礼包
                        ->column('b.c_id,b.num,b.name,b.duration,b.is_give,b.img,b.des,b.target,b.link,c.ur_id,c.type,c.rand_min,c.rand_max,c.name cname,c.gids', 'b.id');
                }
                catch (\Exception $e)
                {
                    $data = [];
                }
                return json_encode($data, true);
            });

        if (is_string($data))
        {
            $data = json_decode($data, true);
        }
        return $data;
    }

    /**
     * 获取新用户注册礼包
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getNewUserRegisterPackage()
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel1)
            ->getDataAndSet(function ()
            {
                try
                {   // 获取生日权益数据
                    $data = $this->alias('b')
                        ->join('wechat_backup_07_18_14_43_00.zl_coupon_attr c', 'b.c_id=c.id')
                        ->where('b.status', 1)
                        ->where('b.type', 2) // 生日权益 type= 1生日权益 2新手礼包
                        ->column('b.c_id,b.num,b.name,b.duration,b.is_give,b.img,b.des,b.target,b.link,c.ur_id,c.type,c.rand_min,c.rand_max,c.name cname,c.gids', 'b.id');
                }
                catch (\Exception $e)
                {
                    $data = [];
                }
                return json_encode($data, true);
            });

        if (is_string($data))
        {
            $data = json_decode($data, true);
        }

        return $data;
    }

    /**
     * 赠送新手礼包优惠券
     * @param int $uid
     * @return bool
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public function registerPackageBoonSend(int $uid): bool
    {
        $couponData = $this->getNewUserRegisterPackage();

        $registerPackageSendRecodeModel = new ZlRegisterPackageSendRecode();
        $hasSendBoon = $registerPackageSendRecodeModel->getUserHasSendPackage($uid);
        if ($hasSendBoon)
        {
            $this->errorMsg = '新手礼包已经赠送过了';
            return false;
        }

        $time = time();
        $userCouponModel = new UserCoupon();
        $ids = [];  // 未使用优惠券ID
        $giveIds = [];// 可赠与优惠券ID
        $this->startTrans();
        try
        {
            foreach ($couponData as $couponItem)
            {
                for ($i = 0; $i < $couponItem['num']; $i++)
                {
                    // 固定过期天数
                    $endTime = $couponItem['duration'] != 0 ? strtotime("+{$couponItem['duration']} day") : 0;

                    $cData = [
                        'uid' => $uid,
                        'c_id' => $couponItem['c_id'],
                        'ur_id' => $couponItem['ur_id'],
                        'start_time' => $time,
                        'end_time' => $endTime,
                        'give_time' => $time,
                        'status' => 0,
                        'price' => $couponItem['type'] == 4 ? mt_rand($couponItem['rand_min'], $couponItem['rand_max']) : 0,
                        'is_give' => $couponItem['is_give'],
                        'create_time' => $time,
                        'update_time' => $time,
                    ];
                    $ucId = $userCouponModel->insertGetId($cData);
                    $ids[$ucId] = $ucId; // 添加未用于ID
                    if ($couponItem['is_give'] == 1)
                    {
                        $giveIds[$ucId] = $ucId;
                    }
                    $gidsArr = explode(',', $couponItem['gids']);

                    $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');
                    // 神策打点 75 获得优惠券 AcquireCoupon
                    SensorsData::track($uid, true, 'AcquireCoupon', [
                        'refer_name' => '自动领取',
                        'refer_link' => 'zhunle_api',
                        'coupon_name' => $couponItem['cname'],
                        'coupon_expire' => date('Y-m-d H:i:s', $endTime),
                        'coupon_type' => $this->couponTypeName[$couponItem['type']],
                        'coupon_range' => $couponRangeArr,
                        'acquire_channel' => '新手礼包',
                        'is_give' => $cData['is_give']?true:false,
                        'acquire_scene' => '系统赠送',
                    ]);
                }
            }
            // 记录领取记录
            $registerPackageSendRecodeModel->save([
                'uid' => $uid,
                'send_boon_ids' => implode(',', array_keys($couponData)),
                'create_time' => $time
            ]);
            $this->commit();
        }
        catch (Exception $e)
        {
            $this->rollback();
            $this->errorMsg = '服务异常';
            Log::write("赠送用户【{$uid}】新手礼包优惠券异常：{$e->getMessage()},line：{$e->getLine()},file:{$e->getFile()}", 'error');
            return false;
        }

        $userCouponModel->listDataAdd($uid, $ids, 1);
        if ($giveIds)
        {   // 可赠与
            $userCouponModel->listDataAdd($uid, $giveIds, 2);
        }
        // 缓存用户新手礼包赠送记录
        CacheManage::getInstance()->setCacheConfig('user.register_package_send_recode', $uid)->setCache('1');
        return true;
    }

    /**
     * 领取生日优惠券
     * @param int $uid
     * @return bool
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public function birthdayCouponGive(int $uid)
    {
        $couponData = $this->getBirthBoon();

        $birthdayBoonGiveRecord = new ZlBirthdayBoonGiveRecord();
        $giveRecordData = $birthdayBoonGiveRecord->getBoonGiveYearList($uid);
        $year = date('Y');
        if (in_array($year, $giveRecordData))
        {
            $this->errorMsg = '今年已经领取过';
            return false;
        }

        $time = time();
        $userCouponModel = new UserCoupon();
        $ids = [];  // 未使用优惠券ID
        $giveIds = [];// 可赠与优惠券ID
        $this->startTrans();
        try
        {
            foreach ($couponData as $couponItem)
            {
                for ($i = 0; $i < $couponItem['num']; $i++)
                {
                    // 固定过期天数
                    $endTime = $couponItem['duration'] != 0 ? strtotime("+{$couponItem['duration']} day") : 0;

                    $cData = [
                        'uid' => $uid,
                        'c_id' => $couponItem['c_id'],
                        'ur_id' => $couponItem['ur_id'],
                        'start_time' => $time,
                        'end_time' => $endTime,
                        'give_time' => $time,
                        'status' => 0,
                        'price' => $couponItem['type'] == 4 ? mt_rand($couponItem['rand_min'], $couponItem['rand_max']) : 0,
                        'is_give' => $couponItem['is_give'],
                        'create_time' => $time,
                        'update_time' => $time,
                    ];
                    $ucId = $userCouponModel->insertGetId($cData);
                    $ids[$ucId] = $ucId; // 添加未用于ID
                    if ($couponItem['is_give'] == 1)
                    {
                        $giveIds[$ucId] = $ucId;
                    }

                    // 神策打点
                    SensorsData::track($uid, true, 'AcquireCoupon', [
                        'refer_name' => '生日领取',
                        'refer_link' => 'wechat_backup_07_18_14_43_00.goddessxzns.com/web/birthday/boon',
                        'coupon_name' => $couponItem['cname'],
                        'coupon_expire' => date('Y-m-d H:i:s', $endTime),
                        'coupon_type' => $this->couponTypeName[$couponItem['type']],
                        'coupon_range' => explode(',',$couponItem['gids']),
                        'acquire_channel' => '生日权益',
                        'is_give' => $cData['is_give']?true:false,
                        'acquire_scene' => '系统赠送',
                    ]);
                }
            }
            // 记录领取记录
            $birthdayBoonGiveRecord->save([
                'uid' => $uid,
                'give_boon_ids' => implode(',', array_keys($couponData)),
                'year' => $year,
                'create_time' => $time
            ]);
            $this->commit();
        }
        catch (Exception $e)
        {
            $this->rollback();
            $this->errorMsg = '服务异常';
            Log::write("领取生日优惠券异常：{$e->getMessage()},line：{$e->getLine()},file:{$e->getFile()}", 'error');
            return false;
        }

        $userCouponModel->listDataAdd($uid, $ids, 1);
        if ($giveIds)
        {   // 可赠与
            $userCouponModel->listDataAdd($uid, $giveIds, 2);
        }
        $giveRecordData[] = $year; // 缓存今年生日的领取年份
        CacheManage::getInstance()->setCacheConfig('user.coupon_birthday_boon_give_record', $uid)->setCache($giveRecordData);
        return true;
    }
}
